################################################################################
#    Name: mockory.py
#    Author: Bryan Kemp (bryan@kempville.com)
#    Description: A Mock factory
#    Copyright (C) Sat Jul 05 23:06:03 2008
#    Version: A01
#
#    ChangeLog:
#      A00 - Sat Jul 05 23:06:03 2008 - Bryan Kemp - Initial release
################################################################################

################################################################################
#    Permission is hereby granted, free of charge, to any person obtaining     
#    a copy of this software and associated documentation files (the           
#    "Software"), to deal in the Software without restriction, including       
#    without limitation the rights to use, copy, modify, merge, publish,        
#    distribute, sublicense, and/or sell copies of the Software, and to         
#    permit persons to whom the Software is furnished to do so, subject to      
#    the following conditions:                                                  
#                                                                              
#    The above copyright notice and this permission notice shall be             
#    included in all copies or substantial portions of the Software.            
#                                                                              
#    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,            
#    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF         
#    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.     
#    IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR          
#    OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,      
#    ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR      
#    OTHER DEALINGS IN THE SOFTWARE.                                            
################################################################################

import posix # to get the UID
import subprocess
import sys

################################################################################
#    Class: MockFactory
#    Description: a wrapper for using mock
################################################################################
class MockFactory:
  
  ##############################################################################
  # Function: __init__
  # Description: The default constructor for the class
  # Input:  None
  #
  # Output: None
  ##############################################################################
  def __init__(self):
    self.mockConfigDir = "mock/etc/"
    self.SRPMSDir = "mock/SRPMS/"
    self.RPMSDir = "mock/RPMS/"
    self.linuxBuilderVersion = "linuxbuilder"
    self.UID = posix.getuid()
    self.DEBUG = False

  ##############################################################################
  # Function: buildRPM
  # Description: use the SRPM to build RPMs
  # Input:  source rpm name
  #
  # Output: Boolean (true if build && createrepo successful
  ##############################################################################
  def buildRPM(self, srcRPMName):
    buildStatus=False
    mockCommand = "sudo mock"
    if self.DEBUG == True:
      mockCommand = mockCommand + " -v"
    mockCommand = mockCommand + " --configdir %s" % self.mockConfigDir
    mockCommand = mockCommand + " -r %s" % self.linuxBuilderVersion
    mockCommand = mockCommand + " --uniqueext=%d" % self.UID
    mockCommand = mockCommand + " --resultdir=%s%s/" % (self.RPMSDir,
                                                      self.linuxBuilderVersion)
    mockCommand = mockCommand + " %s%s" % (self.SRPMSDir, srcRPMName)
    if self.DEBUG == True:
      print "Mock Command: ",mockCommand
    try:
      returnCode = subprocess.call(mockCommand, shell=True)
      if returnCode < 0:
        print >> sys.stderr, "Mock was terminated by signal: ", -returnCode
      elif returnCode == 0:
        if self.DEBUG == True:
          print "Mock completed successfully."
        if self.createRepo() == True:
          buildStatus = True
      else:
        print >> sys.stderr, "Mock failed with error code: ", returnCode
    except OSError, e:
      print >> sys.stderr, "Execution failed:", e
    return buildStatus

  ##############################################################################
  # Function: createRepo
  # Description: creates / updates the RPM repository data
  # Input:  the repository directory (optional)
  #
  # Output: Boolean (true if createrepo successful)
  ##############################################################################
  def createRepo(self, repoName = None):
    createRepoStatus = False
    if repoName == None:
      repoName = "%s%s/" % (self.RPMSDir, self.linuxBuilderVersion)
    repoCommand = "createrepo %s" % repoName
    if self.DEBUG == True:
      print "Createrepo command: %s" % repoCommand
    try:
      returnCode = subprocess.call(repoCommand, shell=True)
      if returnCode < 0:
        print >> sys.stderr, "Createrepo killed by signal: ", -returnCode
      elif returnCode == 0:
        if self.DEBUG == True:
          print "Createrepo completed successfully."
        createRepoStatus = True
      else:
        print >> sys.stderr, "Createrepo failed with return code: ", returnCode
    except OSError, e:
      print >> sys.stderr, "Createrepo call failed:", e
    return createRepoStatus